package cn.net.cfss.fgbp.provider.manage.service;

import cn.net.cfss.fgbp.provider.manage.biz.FscHolidayBiz;
import cn.net.cfss.fgbp.spi.manage.constant.CacheKeyConstant;
import cn.net.cfss.fgbp.spi.manage.constant.HolidayTypeEnum;
import cn.net.cfss.fgbp.spi.manage.dto.FscHolidayDto;
import cn.net.cfss.fgbp.spi.manage.dto.FscTenantDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wutao
 * @version 1.0
 * @date 2021/3/5 15:09
 */
@Slf4j
@Service
public class CacheService {

    @Autowired
    private FscHolidayBiz fscHolidayBiz;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 删除缓存
     */
    public void delete(String key) {
        redisTemplate.delete(key);
    }

    /**
     * 更新节假日缓存信息,缓存类型Hash,key是日期，value是类型
     */
    public void updateHolidayCache(List<FscHolidayDto> list) {
        //删除缓存
        delete(CacheKeyConstant.FSC_CACHE_HOLIDAY);

        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        Map<String, HolidayTypeEnum> map = new HashMap<>();
        for (FscHolidayDto fscHolidayDto : list) {
            map.put(fscHolidayDto.getDate(), fscHolidayDto.getType());
        }

        redisTemplate.opsForHash().putAll(CacheKeyConstant.FSC_CACHE_HOLIDAY, map);
        int expireDay = 1;
        redisTemplate.expire(CacheKeyConstant.FSC_CACHE_HOLIDAY, expireDay, TimeUnit.DAYS);
    }

    /**
     * 节假日查询，通过缓存信息查询当天类型
     * @param date
     * @return
     */
    public HolidayTypeEnum queryHoliday(String date) {
        Object o = redisTemplate.opsForHash().get(CacheKeyConstant.FSC_CACHE_HOLIDAY, date);
        if (o == null) {
            return null;
        } else {
            return (HolidayTypeEnum)o;
        }
    }

    /**
     * 更新租户缓存
     * @param fscTenantDto
     */
    public void updateTenant(FscTenantDto fscTenantDto) {
        Long id = fscTenantDto.getId();
        String key = getTenantKey(id);

        //缓存租户信息，缓存有效时间1天
        Long expire = 1L;
        redisTemplate.opsForValue().set(key, fscTenantDto, expire, TimeUnit.DAYS);
    }

    /**
     * 获取租户缓存的redis key
     */
    public String getTenantKey (Long tenantId) {
        StringBuilder append = new StringBuilder(CacheKeyConstant.FSC_CACHE_TENANT).append(tenantId);
        return append.toString();
    }

    /**
     * 查询缓存失效时间
     * @param key
     * @return
     */
    public Long getExpire (String key) {
        Long expire = redisTemplate.getExpire(key, TimeUnit.MILLISECONDS);
        return expire;
    }



}
